package com.adgox.tiantianbiting.home.category;

import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Messenger;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.adgox.tiantianbiting.R;
import com.adgox.tiantianbiting.bean.UserInfo;
import com.adgox.tiantianbiting.home.programDetail.ProgramDetailActivity;
import com.adgox.tiantianbiting.adapter.CategoryAdapter;
import com.adgox.tiantianbiting.bean.PageBean;
import com.adgox.tiantianbiting.bean.SubProgramBean;
import com.adgox.tiantianbiting.bean.TopBannerBean;
import com.adgox.tiantianbiting.mine.login.LoginActivity;
import com.adgox.tiantianbiting.music.MusicService;
import com.adgox.tiantianbiting.utils.DialogUtils;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.rae.swift.session.SessionManager;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class CategoryActivity extends AppCompatActivity implements CategoryContract.View, OnBannerListener, CategoryAdapter.onItemClickListener {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;

    private int categoryId;
    private String categoryName;
    private CategoryContract.Presenter mPresenter;
    private List<SubProgramBean> programList = new ArrayList<>();
    private int currentPage = 1;
    private int maxPage = 10;
    private int totalPages;
    private CategoryAdapter categoryAdapter;
    private List<TopBannerBean> mBannerList;
    private Intent intentService;
    private CateReceiver receiver;
    private int rvClickPosition;
    private int serviceProgramId;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_category);
        ButterKnife.bind(this);
        new CategoryPresenterImpl(this);
        categoryName = getIntent().getStringExtra("categoryName");
        categoryId = getIntent().getIntExtra("categoryId", -1);
        init();
    }

    private void init() {
        if (categoryId == -1 || "".equals(categoryName)) {
            Toast.makeText(this, "栏目获取出错", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        if (SessionManager.getDefault().isLogin()){
            int userId = ((UserInfo) SessionManager.getDefault().getUser()).getId();
            DialogUtils.checkRandomRed(userId,this,"栏目列表页");
        }

        tvTitle.setText(categoryName);
        DialogUtils.showLoadingDialog(this);
//        mPresenter.getIfShowRedPacket();
        mPresenter.getBanner(categoryId);
        mPresenter.getCategory(categoryId, currentPage, maxPage);
        scrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                if (scrollY == (v.getChildAt(0).getMeasuredHeight()) - v.getMeasuredHeight()) {
                    //加载更多
                    if (currentPage < totalPages) {
                        currentPage++;
                        showLoading();
                        mPresenter.getCategory(categoryId, currentPage, maxPage);
                    } else {
                        Toast.makeText(CategoryActivity.this, "没有更多了", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }

    private void registerReceiver() {
        receiver = new CateReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.adgox.tiantianbiting.music.MusicService");
        this.registerReceiver(receiver, intentFilter);
    }

    private void ifServiceAlive() {
        ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> runningServices = am.getRunningServices(Integer.MAX_VALUE);
        for (ActivityManager.RunningServiceInfo info : runningServices) {
            if (info.service.getClassName().equals("com.adgox.tiantianbiting.music.MusicService")) {
                intentService = new Intent(this, MusicService.class);
                intentService.putExtra("option", "reattach");
                startService(intentService);
            }
        }
    }

    @Override
    public void setPresenter(CategoryContract.Presenter presenter) {
        mPresenter = presenter;
    }

    @Override
    public void onSetData(PageBean<SubProgramBean> pageBean) {
        if ((pageBean == null || pageBean.getData() == null) || pageBean.getData().size() == 0) {
            Toast.makeText(this, "获取数据失败", Toast.LENGTH_SHORT).show();
            return;
        }
        totalPages = pageBean.getTotalPages();
        programList.addAll(pageBean.getData());
        if (categoryAdapter == null) {
            LinearLayoutManager manager = new LinearLayoutManager(this);
            manager.setSmoothScrollbarEnabled(true);
            manager.setAutoMeasureEnabled(true);

            rv.setLayoutManager(manager);
            rv.setHasFixedSize(true);
            rv.setNestedScrollingEnabled(false);
            categoryAdapter = new CategoryAdapter(programList);
            categoryAdapter.setOnItemClickListener(this);
            categoryAdapter.setHasStableIds(true);
            rv.setAdapter(categoryAdapter);
        } else {
//            categoryAdapter.addDatas(pageBean.getData());
            categoryAdapter.setDatas(programList);
        }

        //页面数据刷新完毕后，重新连接service，注册广播
        ifServiceAlive();
        registerReceiver();
    }

    private void showLoading() {
        DialogUtils.showLoadingDialog(this);
    }

    @Override
    public void onGetDataFailed(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onSetBanner(List<TopBannerBean> bannerList) {
        if (bannerList == null || bannerList.size() == 0) {
            Toast.makeText(this, "获取数据失败", Toast.LENGTH_SHORT).show();
            return;
        }
        mBannerList = bannerList;
        ArrayList<String> imgList = new ArrayList<>();

        for (TopBannerBean bean : bannerList) {
            imgList.add(bean.getImageUrl());
        }

        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR)
                .setImageLoader(new ImageLoader() {
                    @Override
                    public void displayImage(Context context, Object path, ImageView imageView) {
                        Glide.with(context).load(path).into(imageView);
                    }
                })
                .setImages(imgList)
                .setDelayTime(3000)
                .isAutoPlay(true)
                .setOnBannerListener(this)
                .start();
    }

    @Override
    public void onGetBannerFailed(String msg) {
        banner.setVisibility(View.GONE);
    }

    @Override
    public void OnBannerClick(int position) {
        if (mBannerList.get(position).getIsH5() == 1) {
            toProgram(mBannerList.get(position).getProgramId(), "天天必听");
        }
    }

    @OnClick(R.id.img_finish)
    public void onViewClicked() {
        finish();
    }

    @Override
    public void onItemClick(View view, CategoryAdapter.ViewType viewType, int position) {
        rvClickPosition = position;
        if (!SessionManager.getDefault().isLogin()) {
            startActivity(new Intent(CategoryActivity.this, LoginActivity.class));
            return;
        }
        if (viewType == CategoryAdapter.ViewType.PLAY) {
            //直接播放
            play(rvClickPosition);
            return;
        }
        //跳转节目详情
        Intent intent = new Intent(this, ProgramDetailActivity.class);
        intent.putExtra("programId", programList.get(rvClickPosition).getId());
        intent.putExtra("programName", programList.get(rvClickPosition).getTitle());
        startActivity(intent);
    }

    private void play(int position) {
        String playUrl = programList.get(position).getPlayUrl();
        if (playUrl == null) {
            Toast.makeText(this, "获取播放地址失败", Toast.LENGTH_SHORT).show();
            return;
        }
        //判断后台播放的节目是否是本节目
        if (serviceProgramId > 0 && serviceProgramId != programList.get(position).getId()) {
            intentService = new Intent(CategoryActivity.this, MusicService.class);
            intentService.putExtra("option", "kill");
            startService(intentService);
            categoryAdapter.setPlayTotalTime(0);
            categoryAdapter.setPlayPostion(0);

        }

        intentService = new Intent(CategoryActivity.this, MusicService.class);
        intentService.putExtra("option", "play");
        intentService.putExtra("messenger", new Messenger(new Handler()));
        intentService.putExtra("path", playUrl);
        intentService.putExtra("programId", programList.get(position).getId());
        intentService.putExtra("clickPosition", 0);
        intentService.putExtra("img", programList.get(position).getShareImageUrl());
        startService(intentService);
        categoryAdapter.setPlayPostion(position);
    }

    private void toProgram(int programId, String programName) {
        if (!SessionManager.getDefault().isLogin()) {
            startActivity(new Intent(CategoryActivity.this, LoginActivity.class));
            return;
        }
        Intent intent = new Intent(CategoryActivity.this, ProgramDetailActivity.class);
        intent.putExtra("programId", programId);
        intent.putExtra("programName", programName);
        startActivity(intent);
    }

    class CateReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();
            String playStatus = bundle.getString("playStatus");
            int currentPosition = bundle.getInt("currentPosition");
            if (currentPosition != 0) {
                categoryAdapter.setPlayCurrentTime(currentPosition);
            }
            if ("play".equals(playStatus)) {
                categoryAdapter.setPlayPostion(rvClickPosition);
                int duration = bundle.getInt("duration");
                if (duration != 0) {
                    categoryAdapter.setPlayTotalTime(duration);
                }
                categoryAdapter.isPlaying(true);
                addHistory();
                serviceProgramId = programList.get(rvClickPosition).getId();
            } else if ("pause".equals(playStatus)) {
                categoryAdapter.isPlaying(false);
            } else if ("continue".equals(playStatus)) {
                categoryAdapter.isPlaying(false);
            } else if ("end".equals(playStatus)) {
                intentService = new Intent(CategoryActivity.this, MusicService.class);
                stopService(intentService);
                categoryAdapter.isPlaying(false);
                categoryAdapter.setPlayCurrentTime(0);
                categoryAdapter.setPlayTotalTime(0);
                categoryAdapter.setPlayPostion(-1);
            } else if ("reattach".equals(playStatus)) {
                serviceProgramId = bundle.getInt("programId");
                //遍历列表数据，看是否有后台正在播放的节目
//                for (SubProgramBean bean : programList){
//                    if (bean.getId() != serviceProgramId) continue;
//
//                }
//                if (serviceProgramId == programId) {
//                    clickPosition = bundle.getInt("clickPosition");
//                    if (adapter != null) {
//                        adapter.setClickPostion(clickPosition);
//                        adapter.notifyDataSetChanged();
//                    }
//                    if (bundle.getBoolean("isPlaying", true)) {
//                        iconPlay.setImageResource(R.drawable.icon_delay);
//                    } else {
//                        iconPlay.setImageResource(R.drawable.icon_play);
//                    }
//                    seekBar.setMax(bundle.getInt("duration"));
//                    tvTotalTime.setText(TimeUtils.MSToTime(bundle.getInt("duration")));
//                    playerProgress.setVisibility(View.VISIBLE);
//                } else {
//                    //打开页和播放页不是同一个节目,不用处理
//                }
            }
        }
    }

    private void addHistory() {
        Gson gson = new Gson();
        HashMap<String, Object> map = new HashMap<>();
        map.put("programId", programList.get(rvClickPosition).getId());
        map.put("status", 0);
        map.put("seasonId", programList.get(rvClickPosition).getSeasonId());
        map.put("userId", ((UserInfo) SessionManager.getDefault().getUser()).getId());
        String s = gson.toJson(map);
        mPresenter.addHistory(s);
    }
}
